package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.OrderPageQueryDTO;
import com.sky.dto.OrdersDTO;
import com.sky.entity.Order;
import com.sky.entity.User;
import com.sky.entity.UserMaterial;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private UserMapper userMapper;

    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void upload(OrdersDTO ordersDTO) {
        try {
            // 验证用户信息
            User user = userMapper.getById(ordersDTO.getUserId());
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }
            
            // 校验电话号码
            if (!ordersDTO.getContactPhone().equals(user.getPhone())) {
                log.error("电话号码不匹配，订单电话：{}，用户电话：{}", ordersDTO.getContactPhone(), user.getPhone());
                throw new RuntimeException("联系电话与用户信息不匹配");
            }
            
            Order order = Order.builder()
                    .number(ordersDTO.getNumber())
                    .productName(ordersDTO.getProductName())
                    .orderAmount(ordersDTO.getOrderAmount())
                    .paymentMethod(ordersDTO.getPaymentMethod())
                    .orderStatus(ordersDTO.getOrderStatus())
                    .orderSource(ordersDTO.getOrderSource())
                    .contactPerson(ordersDTO.getContactPerson())
                    .contactPhone(ordersDTO.getContactPhone())
                    .customerName(ordersDTO.getCustomerName())
                    .orderTime(ordersDTO.getOrderTime())
                    .createTime(ordersDTO.getCreateTime())
                    .updateTime(ordersDTO.getUpdateTime())
                    .status(ordersDTO.getStatus())
                    .payStatus(ordersDTO.getPayStatus())
                    .amount(ordersDTO.getAmount())
                    .userId(ordersDTO.getUserId())
                    .appointmentDate(ordersDTO.getAppointmentDate())  // 添加这行
                    .build();
                    
            log.info("开始插入订单数据：{}", order);
            int rows = orderMapper.insert(order);
            if (rows > 0) {
                log.info("订单数据插入成功，ID：{}", order.getId());

                // 设置当前订单ID到上下文中
                BaseContext.setCurrentOrderId(order.getId());
            } else {
                log.error("订单数据插入失败");
                throw new RuntimeException("订单数据插入失败");
            }
        } catch (Exception e) {
            log.error("订单上传失败：", e);
            throw e;
        }
    }

    @Override
    public PageResult pageQuery(OrderPageQueryDTO orderPageQueryDTO) {
        try {
            log.info("开始分页查询订单，参数：{}", orderPageQueryDTO);
            
            // 参数校验
            if (orderPageQueryDTO.getPage() <= 0) {
                orderPageQueryDTO.setPage(1);
            }
            if (orderPageQueryDTO.getPageSize() <= 0) {
                orderPageQueryDTO.setPageSize(10);
            }
            
            // 设置分页
            PageHelper.startPage(orderPageQueryDTO.getPage(), orderPageQueryDTO.getPageSize());
            
            // 执行查询
            Page<Order> page = orderMapper.pageQuery(orderPageQueryDTO);
            
            // 检查查询结果
            if (page != null) {
                log.info("查询成功，总记录数：{}，当前页数据量：{}", 
                        page.getTotal(), page.getResult().size());
                return new PageResult(page.getTotal(), page.getResult());
            } else {
                log.warn("查询结果为空");
                return new PageResult(0L, null);
            }
        } catch (Exception e) {
            log.error("分页查询订单异常：", e);
            throw new RuntimeException("订单查询失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(String orderNo, String orderStatus) {
        try {
            log.info("开始更新订单状态：订单号={}, orderStatus={}", orderNo, orderStatus);
            int rows = orderMapper.updateStatus(orderNo, orderStatus, LocalDateTime.now());
            if (rows > 0) {
                log.info("订单状态更新成功");
            } else {
                log.error("订单状态更新失败，订单不存在");
                throw new RuntimeException("订单不存在");
            }
        } catch (Exception e) {
            log.error("订单状态更新失败：", e);
            throw e;
        }
    }

    @Override
        public Long getOrderIdByNumber(String orderNumber) {
            return orderMapper.getOrderIdByNumber(orderNumber);
        }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrder(Order order) {
        try {
            log.info("开始更新订单信息：{}", order);
            
            // 设置更新时间
            order.setUpdateTime(LocalDateTime.now());
            
            // 执行更新
            int rows = orderMapper.updateOrder(order);
            if (rows <= 0) {
                throw new OrderBusinessException("订单不存在或更新失败");
            }
            
            log.info("订单信息更新成功");
        } catch (Exception e) {
            log.error("订单信息更新失败：", e);
            throw new OrderBusinessException("订单更新失败：" + e.getMessage());
        }
    }
    
    @Override
    public Order getOrderDetail(Long id) {
        Order order = orderMapper.getById(id);
        if (order == null) {
            throw new OrderBusinessException("订单不存在");
        }
        return order;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMaterialStatus(Long orderId, String materialStatus) {
        try {
            log.info("开始更新订单材料状态：orderId={}, materialStatus={}", orderId, materialStatus);
            int rows = orderMapper.updateMaterialStatus(orderId, materialStatus);
            if (rows > 0) {
                log.info("订单材料状态更新成功");
            } else {
                log.error("订单材料状态更新失败，订单不存在");
                throw new OrderBusinessException("订单不存在");
            }
        } catch (Exception e) {
            log.error("订单材料状态更新失败：", e);
            throw new OrderBusinessException("材料状态更新失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateVisaStatus(Long orderId, String visaStatus) {
        try {
            log.info("开始更新订单签证状态：orderId={}, visaStatus={}", orderId, visaStatus);
            int rows = orderMapper.updateVisaStatus(orderId, visaStatus);
            if (rows > 0) {
                log.info("订单签证状态更新成功");
            } else {
                log.error("订单签证状态更新失败，订单不存在");
                throw new OrderBusinessException("订单不存在");
            }
        } catch (Exception e) {
            log.error("订单签证状态更新失败：", e);
            throw new OrderBusinessException("签证状态更新失败：" + e.getMessage());
        }
    }
}